package com.ht.daoimpl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;

import com.ht.dao.UserDao;
import com.ht.model.User;

@Component
public class UserDaoImpl extends HibernateDao implements UserDao {
	@SuppressWarnings("unchecked")
	public List<User> findUserByExample(User user){
		List<User> results = new ArrayList<User>();
		try {
			results = this.getHibernateTemplate().findByExample("com.ht.model.User", user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return results;
	}

	@Override
	public void insertUser(User user) {
		this.getHibernateTemplate().save(user);
	}
	
	public int insertToUser(User user) {
		int result = super.insert(user);
		return result;
	}
	

	public int deleteUser(User user) {
		int result = super.delete(user);
		return result;
	}

	public int updateUser(User user) {
		int result = this.update(user);
		return result;
	}


	
	public List<User> selectByCon(User user,int curPage ,int pageSize) {
		String hql = "select app from User app where 1=1 ";
		if (user != null) {
			if (user.getId()!= 0) {
				hql = hql + " and Id like '%" + user.getId() + "%' ";
			}
			if (user.getUsername()!= null) {
				hql = hql + " and username like '%" + user.getUsername() + "%' ";
			}
		}
		
		List<User> allemps = super.exeQueryByPage(hql, null,curPage,pageSize);
		
		return allemps;
	}
	
	
	public User getUserByUsername(String name) {
		String hql = "select user from User user where name=?";
		String[] args = new String[1]; 
		args[0] = name ;
		Object o =  super.getUniqueObject(hql, args);
		User user = (o!=null) ? (User)o :null;
		return user;
	}	
	
	
	public User getUserById(User user) {
		Object o = super.get(User.class, user.getId());
		User sa = (o!=null) ? (User)o : null ;
		return sa;
	}
	
	public int getRecordCount(User user) {
		String hql = "select count(*) from User where 1=1 ";
		if (user != null) {
			if (user.getId() != 0) {
				hql = hql + " and id like '%" + user.getId() + "%' ";
			}
			if (user.getUsername() != null) {
				hql = hql + " and username like '%" + user.getUsername() + "%' ";
			}


		}
		Object o = super.getUniqueObject(hql, null);
        int result = Integer.valueOf(o.toString());
		return result;

	}
}
